package com.kupurui.asteacher.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import com.bumptech.glide.Glide;


import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.orhanobut.logger.Logger;


/**
 * Created by Administrator on 2017/9/2.
 */

public class URLImageParser implements Html.ImageGetter {
    TextView mTextView;
    Context context;

    public URLImageParser(Context context,TextView textView) {
        this.context = context;
        this.mTextView = textView;
    }

    @Override
    public Drawable getDrawable(String source) {
//            source = "http://img3.redocn.com/tupian/20150430/mantenghuawenmodianshiliangbeijing_3924704.jpg";
        Log.i("result", "图片路径" + source);
//            Log.i("result", "图片路径" + source.split(",")[1]);

        final URLDrawable urlDrawable = new URLDrawable();
//            byte b[] = Base64.decode(source.split(",")[1],Base64.DEFAULT);

//            Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
//            urlDrawable.bitmap = bitmap;
//            imgv.setImageBitmap(bitmap);
        Log.i("result", "1111");


        if (!source.startsWith("http")){
            Bitmap resource=base64ToBitmap(source.split("base64,")[1]);
            if (resource==null){
                Logger.i("bitmap为空"+source);
                return urlDrawable;
            }
            Bitmap bigImage = big(resource);
            urlDrawable.bitmap = bigImage;
//                    urlDrawable.bitmap = loadedImage;
            urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
            mTextView.invalidate();
            mTextView.setText(mTextView.getText()); // 解决图文重叠
        }else {
            Glide.with(context).load(source).asBitmap().listener(new RequestListener<String, Bitmap>() {
                @Override
                public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
                    Log.i("result", "图片加载失败");
                    Log.e("result", e.toString());
                    return true;
                }

                @Override
                public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    Log.i("result", "图片加载成功");
//                    imgv.setImageBitmap(loadedImage);
                    Bitmap bigImage = big(resource);
                    urlDrawable.bitmap = bigImage;
//                    urlDrawable.bitmap = loadedImage;
                    urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
                    mTextView.invalidate();
                    mTextView.setText(mTextView.getText()); // 解决图文重叠
                    return true;
                }
            }).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    Log.i("result", "图片加载成功2");
                    Bitmap bigImage = big(resource);
                    urlDrawable.bitmap = bigImage;
//                    urlDrawable.bitmap = loadedImage;
                    urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
                    mTextView.invalidate();
                    mTextView.setText(mTextView.getText()); // 解决图文重叠
                }
            });

//        Picasso.with(context).load(source).into(new com.squareup.picasso.Target() {
//            @Override
//            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//                Log.i("result", "图片加载成功2");
//                Bitmap bigImage = big(bitmap);
//                urlDrawable.bitmap = bigImage;
////                    urlDrawable.bitmap = loadedImage;
//                urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
//                mTextView.invalidate();
//                mTextView.setText(mTextView.getText()); // 解决图文重叠
//            }
//
//            @Override
//            public void onBitmapFailed(Drawable errorDrawable) {
//                Log.i("result", "图片加载成功3");
//            }
//
//            @Override
//            public void onPrepareLoad(Drawable placeHolderDrawable) {
//                Log.i("result", "图片加载成功4");
//            }
//        });

//        Glide.with(context).asBitmap().load(source).listener(new RequestListener<Bitmap>() {
//            @Override
//            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                return false;
//            }
//
//            @Override
//            public boolean onResourceReady(Bitmap loadedImage, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
////                Log.i("result", "图片加载成功");
////                    imgv.setImageBitmap(loadedImage);
//                Bitmap bigImage = big(loadedImage);
//                urlDrawable.bitmap = bigImage;
////                    urlDrawable.bitmap = loadedImage;
//                urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
//                mTextView.invalidate();
//                mTextView.setText(mTextView.getText()); // 解决图文重叠
//                return true;
//            }
//        }).into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(Bitmap loadedImage, Transition<? super Bitmap> transition) {
////                    Log.i("result", "图片加载成功2");
////                    imgv.setImageBitmap(loadedImage);
//                Bitmap bigImage = big(loadedImage);
//                urlDrawable.bitmap = bigImage;
////                    urlDrawable.bitmap = loadedImage;
//                urlDrawable.setBounds(0, 0, bigImage.getWidth(), bigImage.getHeight());
//                mTextView.invalidate();
//                mTextView.setText(mTextView.getText()); // 解决图文重叠
//            }
//        });
//            ImageLoader.getInstance().loadImage( source, new SimpleImageLoadingListener() {
//                @Override
//                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//
//                }
//            });
        }

        return urlDrawable;
    }

    public class URLDrawable extends BitmapDrawable {
        protected Bitmap bitmap;

        @Override
        public void draw(Canvas canvas) {
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
            }
        }
    }



    /**
     * base64转为bitmap
     * @param base64Data
     * @return
     */
    public  Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }


    /**
     * Bitmap放大的方法
     */

    private Bitmap big(Bitmap bitmap) {
        Matrix matrix = new Matrix();

        float desityscanle = getDesityScanle();
        float scanle = 1;

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        if (bitmap.getWidth()<width/2){
            if (desityscanle>=4){
                scanle= 2.5f;
            }else if (desityscanle<4&&desityscanle>=3){
                scanle =2f;
            }else if (desityscanle<3&&desityscanle>=2){
                scanle=1.5f;
            }else {
                return bitmap;
            }
        }else{
            if (desityscanle>=4){
                scanle= 2f;
            }else if (desityscanle<4&&desityscanle>=3){
                scanle =1.5f;
            }else if (desityscanle<3&&desityscanle>=2){
                scanle=1f;
            }else {
                return bitmap;
            }
        }

        matrix.postScale(scanle, scanle); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    /**
     * Bitmap缩小的方法
     */

    private Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.8f, 0.8f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }


    public float getDesityScanle() {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        // 设置DensityDpi
//        setDmDensityDpi(dm.densityDpi);
        // 密度因子
        float scale = dm.densityDpi / 160;
//        Log.i("result", "放大比例是" + scale);
        return scale;
    }

}